require "open-uri"
require 'stringio'

class Tools::SiteHealthsController < ApplicationController
  before_filter :authorize, :except => :index_in_show
  layout 'base.html', :only => :stat
  
  def index
    @setting = UserToolSetting.find(params[:setting_id])
  end
  
  def stat
    @setting = UserToolSetting.find(params[:id])
    raise '无权查阅' if @setting.user != current_user
    @how_many_days_ago = (params[:how_many_days_ago].blank? ? 0 : params[:how_many_days_ago].to_i)
    @heart_beats = @setting.stat_on(@how_many_days_ago.days.ago.to_date).try(:site_heart_beats) || []
    @seo_title = "麦吐司网-#{@setting.name}-健康状况-综合分析"
    @seo_keywords = '免费,有趣,实用,吐司,#{@setting.name},站长,健康状况,综合分析'
    @seo_description = @seo_title
    respond_to do |format|
      format.html do 
      end
      format.js do 
        render :layout => false
      end
    end
  end
  
  def edit
    edit_in_show
  end
  
  def update
    @setting = UserToolSetting::SiteHealth.find(params[:id])
    @tool = @setting.tool
    if @setting.update_attributes(params["setting_#{@setting.id}"])
      redirect_to :action => :index, :format => :js, :setting_id => @setting.id
    else
      render :edit
    end
  end
  
  def copy
    @setting  = UserToolSetting::SiteHealth.find(params[:id])
    @new = UserToolSetting::SiteHealth.new(
      @setting.attributes.keys.each_with_object({}) do |key,hash|
        hash[key] = @setting.attributes[key] unless [:id,
          :created_at,
          :updated_at,
          :emails_count,
          :sms_count         
        ].include?(key)
      end
    )
    @new.save
    @settings = UserToolSetting.all_by_current_user_by_column @new.column
  end
  
  def destroy
    @setting = UserToolSetting::SiteHealth.find(params[:id])
    render :text => '', :status => @setting.destroy ? 200 : 500
  end
    
  def index_in_show
    @tool = Tool.find_by_code('site_health')
    @settings = UserToolSetting::SiteHealth.find_all_by_user_id_and_tool_id(current_user_id, @tool.id)
  end
  
  def new_in_show
    @tool = Tool.find_by_code('site_health')
    @setting = UserToolSetting::SiteHealth.new(
      :column => @tool.default_column,
      :site_url => 'http://'
    )
  end
  
  def create_in_show    
    @tool = Tool.find_by_code('site_health')
    @setting = UserToolSetting::SiteHealth.new(params[:user_tool_setting_site_health])
    @setting.attributes = {
      :user_id => current_user_id,
      :tool_id => @tool.id
    }
    if @setting.save
      redirect_to :action => :index_in_show, :format => :js
    else
      render :new_in_show
    end
  end
  
  def edit_in_show    
    @setting = UserToolSetting::SiteHealth.find(params[:id])
    @tool = Tool.find_by_code('site_health')
  end
  
  def update_in_show
    @setting = UserToolSetting::SiteHealth.find(params[:id])
    @tool = @setting.tool
    if @setting.update_attributes(params[:user_tool_setting_site_health])
      redirect_to :action => :index_in_show, :format => :js
    else
      render :edit_in_show
    end
  end
  
  def destroy_in_show
    @setting = UserToolSetting::SiteHealth.find(params[:id])
    render :text => '', :status => @setting.destroy ? 200 : 500
  end
  
  def send_email
    send_email_and_render do
      UserToolSetting::SiteHealth.find(params[:id]).send_email!
    end
  end
  
  def send_sm
    send_sm_and_render do 
      UserToolSetting::SiteHealth.find(params[:id]).syn_send_sm!(:by => current_user.fetion_version)
    end 
  end
  
  def test_site_heart_beat
    begin
      if SiteHeartBeat.take_pulse_by_url_and_content! params[:url], params[:content]
        render :text => '成功把到网站的脉了！', :status => 200
      else
        render :text => '脉象不对，该URL不包含匹配内容', :status => 500
      end
    rescue  SocketError
      render :text => '没摸着脉，URL写错了', :status => 500
    rescue OpenURI::HTTPError
      render :text => '没摸着脉，URL写错了', :status => 500
    rescue Errno::ENOENT,URI::InvalidURIError
      render :text => '没摸着脉，URL写错了', :status => 500
    end
  end
  
  private 
  def match?(html_page,content)
    html_page.each do |line|
      #logger.debug "====match:#{content}====#{line.match(content)}======"
      #logger.debug line
      #logger.debug "=============="
      return true if line.match(content)
    end
    return false
  end
  
end
